package org.gjy.m8.xml;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-11-19 17:11:01
 */
public class XmlUtil {

    public static List<String> parseXml(String xml, String expr) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(false);
            dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
            dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(new StringReader(xml)));
            XPath xp = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList) xp.compile(expr).evaluate(doc, XPathConstants.NODESET);
            Transformer tf = TransformerFactory.newInstance().newTransformer();
            tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

            List<String> out = new ArrayList<>();
            for (int i = 0; i < nodes.getLength(); i++) {
                StringWriter sw = new StringWriter();
                tf.transform(new DOMSource(nodes.item(i)), new StreamResult(sw));
                out.add(sw.toString());
            }
            return out;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
